package com.cby.android.library.base

import android.app.Application
import com.cby.android.library.mvi.PageIntent
import com.cby.android.library.mvi.PageState

abstract class BasePageStateViewModel<T>(application: Application) : BaseStateViewModel<PageState<T>, PageIntent>(application) {

    private val listCache: MutableList<Any> = mutableListOf()

    private var currentPage = 0

    private fun loadData() {
        fetchDataWithNoStatus{
            if(currentPage == firstPageIndex() && listCache.isEmpty()) {
                showLoading()
            }
            // 页面数据请求
            val response = loadPageData(currentPage)
            // viewModel层的数据缓存，用来判断页面显示状态
            cacheListData(response)
            if(currentPage == 0 && response.isEmpty()) {
                showEmpty()
            }else{
                updateState(PageState(list = response as MutableList<T>,
                    page = currentPage))
                showContent()
            }
        }
    }

    override fun showError(errorMsg: String?) {
        if(currentPage > 0) {
            updateState(PageState(errorMsg = errorMsg))
        }else{
            super.showError(errorMsg)
        }

    }

    abstract suspend fun loadPageData(page: Int):MutableList<T>

    override fun dispatch(intent: PageIntent) {
        when(intent) {
            PageIntent.LoadFirstPageIntent -> {
                currentPage = 0
                loadData()
            }
            PageIntent.LoadMorePageIntent -> {
                currentPage++
                loadData()
            }
        }
    }

    private fun cacheListData(data: MutableList<T>) {
        // 第一页数据清除
        if(currentPage == firstPageIndex()) {
            listCache.clear()
        }
        // 缓存数据
        listCache.addAll(listOf(data))
    }

    open fun firstPageIndex() = 0
}